<template>
  <layout>
    <!-- 顶部操作 -->
    <section slot="search">
      <custom-form
        ref="search-form"
        class="search-form"
        v-model="tableSearch"
        layout="inline"
        mode="search"
        :FormList="searchColumns"
      >
        <a-button
          class="action-button"
          type="primary"
          icon="search"
          @click="search()"
        >搜索</a-button>
        <a-button
          class="action-button"
          type="primary"
          auth="admin.add"
          icon="plus"
          @click="tableAdd"
        >添加</a-button>
      </custom-form>
      <!-- <a-input placeholder="产品名称或者编号" v-model="tableSearch.searchKey" allowClear style="width: 200px;" /> -->
    </section>

    <!-- 产品列表 -->
    <a-spin :spinning="tableLoading">
      <a-table
        :dataSource="tableData"
        :columns="tableColumns"
        :rowKey="record => record.usr_id"
        :customRow="customTableRow"
        :pagination="false"
        table-layout="fixed"
        :scroll="{
          y: tableClientHeight + 180,
          x: '100%'
        }"
        bordered
      >
        <template
          slot="status"
          slot-scope="row"
        >
          <!-- <span
            v-if="+row.zt === 1"
            style="color: red"
          >待审核</span> -->
          <span>
            {{getLabel(row.statu, [], 'statu')}}
            <!-- <a-switch
              checkedChildren="有效"
              unCheckedChildren="无效"
              :checked="+row.statu === 1 ? true : false"
              @change="(val) => handleUpdateStatus(val, row)"
            /> -->
          </span>
        </template>
        <template
          slot="s_a_id"
          slot-scope="row"
        >
          {{row.s_a_nam}}
          <!-- {{getAreaLabelFromId(row.s_a_id)}} -->
        </template>
        
        <template
          slot="pow_gp_id"
          slot-scope="row"
        >
          {{getLabel(row.pow_gp_id, [], 'pow_gp_id')}}
        </template>
        <template
          slot="task_ids"
          slot-scope="row"
        >
          <a-tooltip placement="topLeft">
            <template slot="title">
              <span>{{getLabel(row.task_ids, [], 'task_ids')}}</span>
            </template>
            <a-tag color="red">已授权{{row.task_ids.split(',').length || 0}}个项目</a-tag>
          </a-tooltip>
        </template>
        <!-- 按钮区 -->
        <template
          slot="action"
          slot-scope="row"
        >
          <a-button-group>
            <a-button
              class="action-button"
              type="link"
              auth="admin.edit"
              @click="handleTableEdit(row)"
            >编辑</a-button>
            <a-popconfirm
              title="您确认要删除该条数据?"
              ok-text="确认"
              cancel-text="取消"
              @confirm="tableDel(row)"
            >
              <a-button
                class="action-button"
                type="link"
                auth="admin.delete"
              >删除</a-button>
            </a-popconfirm>
            <a-button
              class="action-button"
              type="link"
              auth="admin.update-password"
              @click="handlerUpdatePassword(row)"
            >修改密码</a-button>
          </a-button-group>
          
          <!-- <a-button
            class="action-button"
            type="primary"
            size="small"
            @click="handleTableEdit(row)"
          >授权</a-button>
          <a-button
            class="action-button"
            type="primary"
            size="small"
            @click="handleTableEdit(row)"
          >项目管理</a-button> -->
        </template>
      </a-table>
    </a-spin>

    <!-- 产品列表分页器 -->
    <a-pagination
      slot="paging"
      :pageSizeOptions="pageSizes"
      :total="total"
      showSizeChanger
      :show-total="showTotal"
      :pageSize="pageSize"
      v-model="currentPage"
      @showSizeChange="changePageSize"
      @change="changePage"
    >
    </a-pagination>

    <!-- 编辑产品数据 -->
    <a-modal
      :visible="visible"
      :title="visibleTitle"
      centered
      @ok="customSubmit"
      @cancel="visible = false"
    >
      <custom-form
        ref="custom-form"
        class="custom-form"
        v-model="currentRow"
        :FormList="formColumns"
        :mode="formMode"
        layout="horizontal"
        v-bind="formItemLayout"
      ></custom-form>
      <!-- <section slot="footer"> -->
      <!-- <a-button @click="handleSubmit">提交</a-button> -->
      <!-- </section> -->
    </a-modal>

  </layout>
</template>

<script lang="ts">
import { Mixins, Component, Watch, Vue, Prop } from 'vue-property-decorator'
import { State, Mutation, Getter, namespace } from 'vuex-class'
import EventsMixin from '@/mixin/events'
import { TableMixin, AuthMixin, AppMixin } from '@/mixin'
import { formatTree } from '@/utils/tools'

import { TableLayout } from '@/layouts'
import CustomForm from '@/components/src/Form'
import { userServices, IAdmin, IArea } from '@/common/services'
import { poserServices } from '@/common/services/power'
import { publicServices } from '@/common/services/public'
import { userModule } from '@/store/modules/user'
import Password from './password.vue'
import { message } from 'ant-design-vue'
import md5 from 'js-md5'

@Component({
  components: {
    Layout: TableLayout,
    CustomForm,
    Password
  }
})
export default class AdminList extends Mixins(
  EventsMixin,
  TableMixin,
  AuthMixin,
  AppMixin
) {
  @Prop({
    type: String
  })
  public currentAreaId!: string

  // 产品列表搜索条件
  public tableSearch = {
    next: '1'
  }

  // 产品列表表格信息
  public columns: ITable.IColumn[] = [
    // {
    //   title: '用户编号',
    //   dataIndex: 'usr_id',
    //   key: 'usr_id',
    //   form: {
    //     type: 'a-input',
    //     placeholder: '编号自动生成',
    //     disabled: true
    //   },
    //   width: 80
    // },
    {
      title: '用户编号',
      dataIndex: 'usr_id',
      key: 'usr_id',
      form: {
        type: 'a-input',
        placeholder: '编号自动生成',
        disabled: true
      },
      width: 80
    },

    // 搜索
    {
      title: '用户范围',
      width: 100,
      dataIndex: 'next',
      key: 'next',
      form: {
        type: 'a-radio-group',
        dict: [
          {
            label: '本级',
            value: '1'
          },
          {
            label: '下一级',
            value: '2'
          },
          {
            label: '辖区',
            value: '0'
          }
        ],
        isShowQuery: true,
        isShowList: false,
        isShowFrom: false,
        isShowAll: false
      }
    },

    {
      title: '所属行政区',
      key: 's_a_id',
      width: this.isLargeScreen ? 'auto' : 200,
      scopedSlots: { customRender: 's_a_id' },
      form: {
        type: 'a-tree-select',
        placeholder: '请选择所属行政地区',
        // treeDataSimpleMode: true,
        treeData: [],
        // showSearch: true,
        treeNodeFilterProp: 'title',
        loadData: this.onLoadData,
        dropdownStyle: {
          'overflow-y': 'scroll',
          maxHeight: "600px"
        },
        replaceFields: { title: 's_a_nam', key: 's_a_id', value: 's_a_id', children: 'children' },
        handler: {
          change: () => {
            // this.getPro
          }
        }
      }
    },
    // {
    //   title: '所属行政区',
    //   dataIndex: 's_a_nam',
    //   key: 's_a_nam',
    //   width: 100,
    //   form: {
    //     type: 'a-input',
    //     placeholder: '请输入关键字',
    //     isShowQuery: true,
    //     isShowList: false,
    //     isShowFrom: false
    //   }
    // },
    {
      title: '登录名',
      dataIndex: 'usr_act',
      key: 'usr_act',
      width: 100,
      form: {
        type: 'a-input',
        placeholder: '请输入登录名',
        isShowQuery: true,
        validate: '*',
        disabled: [
          this.isAdmin ? '' : 'edit'
        ]
      }
    },
    {
      title: '身份证号',
      dataIndex: 'usr_sfz',
      key: 'usr_sfz',
      width: 160,
      form: {
        type: 'a-input',
        placeholder: '请输入身份证号',
        isShowQuery: false
      }
    },
    {
      title: '手机号码',
      dataIndex: 'usr_tel',
      key: 'usr_tel',
      width: 110,
      form: {
        type: 'a-input',
        placeholder: '请输入手机号码'
      }
    },
    {
      title: '真实姓名',
      dataIndex: 'usr_nickname',
      key: 'usr_nickname',
      width: 80,
      form: {
        type: 'a-input',
        placeholder: '请输入真实姓名',
        isShowQuery: true
      }
    },
    {
      title: '工作单位',
      dataIndex: 'work_place',
      key: 'work_place',
      width: 180,
      form: {
        type: 'a-input',
        placeholder: '请输入工作单位',
        isShowQuery: true
      }
    },
    {
      title: '用户权限',
      key: 'pow_gp_id',
      width: 120,
      form: {
        type: 'a-select',
        placeholder: '请选择用户权限',
        dict: [],
        isShowQuery: true,
        validate: '*',
        allowClear: true
      },
      scopedSlots: { customRender: 'pow_gp_id' }
    },
    {
      title: '授权项目',
      key: 'task_ids',
      width: 200,
      scopedSlots: { customRender: 'task_ids' },
      form: {
        type: 'a-select',
        placeholder: '请选择授权项目',
        mode: 'multiple',
        validate: '*',
        stringToArray: true,
        dict: []
      }
    },
    {
      title: '备注',
      dataIndex: 'readme',
      key: 'readme',
      width: 180,
      form: {
        type: 'a-textarea',
        placeholder: '请输入备注'
      }
    },
    {
      title: '状态',
      key: 'statu',
      width: 60,
      scopedSlots: { customRender: 'status' },
      form: {
        type: 'a-radio-group',
        placeholder: '请选择状态',
        validate: '*',
        isShowQuery: false,
        defaultValue: 1,
        dict: [
          {
            label: '有效',
            value: '1'
          },
          {
            label: '无效',
            value: '2'
          }
        ]
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 160,
      fixed: 'right',
      scopedSlots: { customRender: 'action' }
    }
  ]

  public tableApi = {
    list: userServices.getAdminList,
    add: userServices.updateAdmin,
    edit: userServices.updateAdmin,
    del: userServices.deleteAdmin,
    imageUpload: 'uploadStoreImage',
    imageRemove: 'delStoreImage'
  }

  get currentSId() {
    return userModule.userInfo.admin_info.s_a_id
  }

  get isAdmin () {
    return userModule.isAdmin
  }

  public mounted() {
    this.tableLoading = true
    // this.getAreaList()
    this.onLoadData()
    Promise.all([this.getProjects(), this.getPowerGroupList()]).then(_ => {
      this.getData()
    })
  }

  @Watch('currentAreaId', { immediate: true })
  public handlerCurrentAreaIdChange() {
    this.commonParams.s_a_id = this.currentAreaId
    this.getData()
  }

  public async getData() {
    const res = await this.getTableList()
  }

  // 设置密码
  public handlerUpdatePassword(row: IAdmin) {
    this.$dialog(Password,
      // component props
      {
        record: {},
        on: {
          ok () {
          },
          cancel () {
            console.log('cancel 回调')
          },
          close () {
            console.log('modal close 回调')
          }
        }
      },
      // modal props
      {
        title: '修改密码',
        width: 500,
        centered: true,
        maskClosable: false,
        okText: '确定',
        cancelText: '取消',
        on: {
          async ok() {
            // @ts-ignore
            const password = this.$refs._component.getPassword()
            if (!password) {
              return false
            }

            await userServices.updateAdminPassword({
              usr_id: row.usr_id,
              pswd: md5(password)
            })

            message.success('更新成功')
            return true;
          }
        }
      })
  }

  // 获取权限列表
  public getPowerGroupList() {
    return poserServices.getPowerGroupList().then(res => {
      this.changeDict(
        'pow_gp_id',
        res.data.map(item => {
          return {
            label: item.pow_gp_nam,
            value: item.pow_gp_id
          }
        })
      )
    })
  }

  // 获取项目列表
  public getProjects() {
    return userServices.getAdminProjectsList({
      s_a_id: this.currentSId
    }).then(res => {
      this.changeDict(
        'task_ids',
        res.data.map(item => {
          return {
            label: item.task_nam,
            value: item.task_id
          }
        })
      )
    })
  }

  // 地区数据
  public area: {
    map: Record<string, IArea>,
  } = {
    map: {}
  };

  // 通过地区编码获取地区名称
  public getAreaLabelFromId(id: string) {
    const len = [2, 2, 2, 3, 3, 2];
    if (id.length < 2) return '';
    let index = 0;
    let label = '';
    let current = ''
    for (let i = 0; i < len.length; i++) {
      const temp = id.substr(index, len[i])
      // 确保是完整的字符串
      if (temp.length !== len[i]) break;
      current += temp;
      index += len[i];
      const tempLabel = this.area.map[current]?.s_a_nam || '';
      if (tempLabel !== '市辖区') {
        label += tempLabel
      }
    }
    return label
  }

  public getAreaList() {
    return publicServices.getAreaList({
      s_a_id: this.currentSId
    }).then(_ => {
      const data = _.data;
      console.time('start')
      const treeData = Object.freeze(formatTree(data, { id: 's_a_id', parentId: 's_up_id' }))
      console.timeEnd('start')
      this.changeDict('s_a_id', treeData, 'treeData')
      
      // 格式化map数据
      for (let i =0; i < data.length; i++) {
        // @ts-ignore
        const item = data[i];
        this.area.map[item.s_a_id] = item;
      }
    })
  }

  public async onLoadData(treeNode?: any) {
    const res = await publicServices.getAreaLazy({
      s_a_id: treeNode ? treeNode.dataRef.s_a_id : this.currentSId || '0'
    })
    // 判断是否是叶子节点
    // @ts-ignore
    const treeData = res.data.map(item => {
      if (item.s_a_id.length === 14) {
        // @ts-ignore
        item.isLeaf = true
      }
      return item
    })
    if (!treeNode) {
      this.changeDict('s_a_id', treeData, 'treeData')
    } else {
      treeNode.dataRef.children = treeData
      const currentTreeData = this.columns.find((column) => {
        return 's_a_id' === column.key && column.form;
      })
      this.changeDict('s_a_id', [...(currentTreeData?.form?.treeData || [])], 'treeData')
    }
  }

  // 编辑前数据预处理
  public async handleTableEdit(row: any) {
    this.tableEdit(Object.assign({}, row, {
      s_a_id: row.s_a_nam,
      _s_a_id: row.s_a_id
    }))
    this.visibleTitle = '个人信息编辑'
  }

  // 自定义提交
  public customSubmit() {
    this.handleSubmit({}, true, (params: any) => {
      if (params.s_a_id === params.s_a_nam) {
        params.s_a_id = params._s_a_id
      }
      return params
    })
  }
}
</script>

<style scoped>
.action-button {
  margin: 0px 10px 0px 10px;
}
.form-item-class {
  margin-bottom: 0px;
}
.img-box {
  width: 100px;
  height: 100px;
  margin: 10px;
}
.item-blue {
  color: #1989fa;
}
</style>
